/**
 * Created by 69466 on 2018/9/13.
 */
import React, { Component, forwardRef, useImperativeHandle, useState } from "react";
import {StyleSheet} from 'react-native';
import {Button, Dialog, View} from 'react-native-ui-lib';
import {Calendar, LocaleConfig} from 'react-native-calendars';
import moment from 'moment';
import {isAndroid} from '../../configs/platform';

LocaleConfig.locales['fr'] = {
  monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
  monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
  dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
  dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
  today: 'Aujourd\'hui',
};
LocaleConfig.defaultLocale = 'fr';
/**
 * 日历对话框
 */
const DatePickerDialog=({callBack},ref)=> {
  const [isOpen, setIsOpen] = useState(false);
  const [current, setCurrent] = useState(moment().format('YYYY-MM-DD'));
  const [startDay, setStartDay] = useState(moment().format('YYYY-MM-DD'));
  const [endDay, setEndDay] = useState(moment().format('YYYY-MM-DD'));

  useImperativeHandle(ref, () => ({
    show: (startDay, endDay,current = getNowFormatDateYMD()) => {
      setIsOpen(true)
      if (startDay && endDay) {
        setStartDay(startDay)
        setEndDay(endDay)
      }
      else{
        setCurrent(current)
      }
    }
  }))

  const renderPannableHeader = () => {
    return (
      <View row spread paddingT-20 paddingH-16 paddingB-6>
        <Button label={'取消'} outline borderRadius={4} size={'small'} onPress={()=>setIsOpen(false)}/>
        <Button label={'确定'} borderRadius={4} size={'small'} onPress={() => {
           callBack &&  callBack(startDay, endDay);
          setIsOpen(false);
        }}/>
      </View>
    );
  };

    let markdays = {};

    let sameDay = false;
    if (moment(startDay).isSame(moment(endDay))) {
      sameDay = true;
      markdays[startDay] = {selected: true, marked: true, dotColor: '#F9D63B'};
    } else {
      markdays[startDay] = {startingDay: true, color: '#F9D63B', textColor: 'white'};
      let diff = moment(endDay).diff(moment(startDay), 'days');
      for (let i = 0; i < diff - 1; i++) {
        let day = moment(startDay).add(i + 1, 'day').format('YYYY-MM-DD');
        markdays[day] = {marked: true, color: '#F9D63B', textColor: 'white'};
      }
      markdays[endDay] = {endingDay: true, color: '#F9D63B', textColor: 'white'};
    }


    // logger('当前日期', markdays);
    return (
      <Dialog
        migrate
        containerStyle={styles.roundedDialog}
        visible={isOpen}
        width={'100%'}
        bottom
        onDismiss={()=>setIsOpen(false)}
        renderPannableHeader={()=>renderPannableHeader()}
        pannableHeaderProps={''}

      >
        <Calendar
          // Initially visible month. Default = Date()
          markingType={sameDay ? 'simple' : 'period'}
          markedDates={markdays}
          current={current}

          // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
          // minDate={}
          // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
          // maxDate={moment().format('YYYY-MM-DD')}
          // Handler which gets executed on day press. Default = undefined
          onDayPress={(day) => {
            logger('点击日期', day.dateString, startDay, endDay);
            if (moment(day.dateString).isAfter(endDay) || moment(day.dateString).isSame(startDay)) {
              setEndDay(day.dateString);
            }
            else if (moment(day.dateString).isBetween(startDay, endDay))
            {
              setEndDay(day.dateString);
            }
            else if (moment(day.dateString).isBefore(startDay) || moment(day.dateString).isSame(endDay)) {
              setStartDay(day.dateString);
            }
          }}
          // Handler which gets executed on day long press. Default = undefined
          onDayLongPress={(day) => {
            console.log('selected day', day);
          }}
          // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
          monthFormat={'yyyy-MM-dd'}
          // Handler which gets executed when visible month changes in calendar. Default = undefined
          onMonthChange={(month) => {
            console.log('month changed', month);
          }}

          // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
          firstDay={1}
          theme={{
            backgroundColor: '#ffffff',
            calendarBackground: '#ffffff',
            textSectionTitleColor: '#2A2A2A',
            selectedDayBackgroundColor: '#F9D63B',
            selectedDayTextColor: '#ffffff',
            todayTextColor: '#F9D63B',
            dayTextColor: '#2d4150',
            textDisabledColor: '#d9e1e8',
            dotColor: '#F9D63B',
            selectedDotColor: '#ffffff',
            arrowColor: '#F9D63B',
            disabledArrowColor: '#d9e1e8',
            monthTextColor: '#2A2A2A',
            indicatorColor: '#2A2A2A',
            // textDayFontFamily: 'monospace',
            // textMonthFontFamily: 'monospace',
            // textDayHeaderFontFamily: 'monospace',
            textDayFontWeight: '300',
            textMonthFontWeight: 'bold',
            textDayHeaderFontWeight: '300',
            textDayFontSize: 16,
            textMonthFontSize: 16,
            textDayHeaderFontSize: 16,
            'stylesheet.day.period': {
              base: {
                overflow: 'hidden',
                height: 34,
                alignItems: 'center',
                width: 38,
              }
            }
          }}
        />
      </Dialog>
    );
}
export default forwardRef(DatePickerDialog);

const styles = StyleSheet.create({
  roundedDialog: {
    backgroundColor: 'white',
  },
  content: {
    fontSize: 14,
    color: '#031133',
    lineHeight: 25,
    minHeight: 50,
  },
});


